package com.github.defense.plugin.gray.context;


import com.github.defense.plugin.gray.enums.GrayType;
import com.github.defense.plugin.gray.request.GrayRequest;
import lombok.*;

import java.util.Objects;

/**
 * 路由信息本地缓存
 *
 * @Author: lettger
 * @Date: 2021/6/7 11:41 上午
 */
@Builder
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class RoutingLocalContext {

    private static final ThreadLocal<RoutingLocalContext> contextLocal = ThreadLocal.withInitial(RoutingLocalContext::new);

    /**
     * 请求信息
     */
    private GrayRequest request;

    /**
     * 灰度参与方组件
     */
    private GrayType grayType;

    /**
     * 设置路由信息
     */
    public static void setContextLocal(RoutingLocalContext context) {
        contextLocal.set(context);
    }

    /**
     * 获取当前线程中的路由信息
     *
     * @return
     */
    public static RoutingLocalContext getContextLocal() {
        return contextLocal.get();
    }

    /**
     * 移除本地线程路由信息
     */
    public static void removeLocalContext() {
        if (Objects.nonNull(contextLocal.get())) {
            contextLocal.remove();
        }
    }
}
